﻿using System;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Collections.Generic;

namespace RealState.Utils
{
    public static class Converter
    {
        public static string MD5Encrypt(string input)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] outputBytes = null;
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            outputBytes = md5.ComputeHash(inputBytes);

            return BitConverter.ToString(outputBytes).ToUpper().Replace("-", string.Empty);
        }

        public static byte[] ToOracleBLOB(string input)
        { return UTF8Encoding.UTF8.GetBytes(input); }
        public static string ToUTF8(byte[] input)
        {
            return UTF8Encoding.UTF8.GetString(input);
        }
        public static string ToUTF8(string input)
        {
            string[] inputs = input.Split('-');
            byte[] results = new byte[inputs.Length];

            for (int i = 0; i < inputs.Length; i++)
            { results[i] = Convert.ToByte(inputs[i]); }

            return UTF8Encoding.UTF8.GetString(results);
        }
        public static bool IsNumeric(string input)
        {
            double output = 0;
            return double.TryParse(input, out output);
        }

        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection props =
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                //table.Columns.Add(prop.Name, prop.PropertyType);
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            }
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item) ?? DBNull.Value; ;
                }
                table.Rows.Add(values);
            }
            return table;
        }

    }
}


